<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use think\Controller;
use OSS\OssClient;
/**
 * 上传
 * Class Upload
 * @package app\home\controller
 */
class Upload extends Controller
{
    protected $accessKeyId = 'LTAIUZZ0EO0Xlz0c';
    protected $accessKeySecret = 'ZPPOxFBERpKvaw4uO5oZVbdgnd5cRd';
    protected $endpoint = 'http://oss-cn-hangzhou.aliyuncs.com';
    protected $bucket = 'fushan';

    protected $endpoint1 = 'http://oss-cn-beijing.aliyuncs.com';
    protected $bucket1 = 'fushance';
    /**
     * [add  图片上传]
     * @param
     * @return json
     * @author [C。]
     */
    public function add()
    {
        $param = input('param.');
        if (!empty($_FILES['file']['name'])) {
            if($_FILES['file']['size'] > 10*1024*1024){
                return admin_json(-2,'图片不能超过10M');
            }
            $fileName = $_FILES['file']['name'];    //得到文件全名
            $dotArray = explode('.', $fileName);    //把文件名安.区分，拆分成数组
            $type = end($dotArray);
//            if ($type != "png" || $type != "gif" || $type != "jpeg" || $type != "bmp" || $type != "jpg") {
//                return admin_json(0, '请上传图片文件！');
//            }
            //取数组最后一个元素，得到文件类型
            $uploaddir = "upload/";//设置文件保存目录 注意包含

            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true);
            }
            $path = $uploaddir . md5(uniqid(rand())) . '.' . $type; //产生随机文件名
            //$path = "images/".$fileName; //客户端上传的文件名；
            //下面必须是tmp_name 因为是从临时文件夹中移动
            move_uploaded_file($_FILES['file']['tmp_name'], $path); //从服务器临时文件拷贝到相应的文件夹下
            $image = \think\Image::open('./'.$path);
            $image->thumb(800, 800)->save('./'.$path);
            if (!file_exists($path)) {
                $ret['res'] = "0";
                $ret['msg'] = "上传文件丢失!";
                return json_encode($ret);
            }
        }else {
            return admin_json(-2,'上传文件失败');
        }
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = $this->endpoint;
        $bucket= $this->bucket;
        // 文件名称
        if(empty($param['path'])){
            $object = 'FS'.md5(uniqid(rand()));
        }else{
            $object = $param['path'].'/'.'FS'.md5(uniqid(rand()));
        }

        // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
        $filePath = $path;

        try{
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
            $ossClient = (array)$ossClient;
        } catch(OssException $e) {
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1,$e->getMessage());
        }
        unlink($filePath);
        return admin_json(1,'上传成功',[
            'url'=>array_values($ossClient)[4],
            'filename'=>$object
        ]);
    }
    /**
     * [del  图片删除]
     * @param
     * @return json
     * @author [C。]
     */
    public function del()
    {
        $param = input('param.');
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = $this->endpoint;
        $bucket= $this->bucket;
        if(empty($param['path'])){
            $object = $param['file'];
        }else{
            $object = $param['path'].'/'.$param['file'];
        }
        try{
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->deleteObject($bucket, $object);
        } catch(OssException $e) {
            systembug($e->getMessage(),2,$this->url);
            return;
        }
        return admin_json(1,'删除成功');
    }
    /**
     * [save  保存图片]
     * @param
     * @return json
     * @author [C。]
     */
    public function save($objectname)
    {
        //取数组最后一个元素，得到文件类型
        $uploaddir = "oss_save/";//设置文件保存目录 注意包含
        if (!file_exists($uploaddir)) {
            mkdir($uploaddir, 0755, true);
        }
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = $this->endpoint;
        $bucket= $this->bucket;
        // <yourObjectName>表示您下载OSS文件时需要指定的文件路径，例如abc/123.jpg。
        $object = $objectname;
        // <yourLocalFile>本地指定的文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        $localfile = ROOT_PATH.'public/oss_save/'.time().rand(1,99).'.png';
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $localfile
        );

// 使用try catch捕获异常，如果捕获到异常，则说明下载失败；如果没有捕获到异常，则说明下载成功。
        try{
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->getObject($bucket, $object, $options);

        } catch(OssException $e) {
            systembug($e->getMessage(),2,$this->url);
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        return $localfile;
    }
}